import { useTranslation } from "react-i18next";
import { InfiniteScroll, Popover } from "antd-mobile";
import Styles from "./STC.module.less";
import { useEffect, useState } from "react";
import { FileOutline } from "antd-mobile-icons";

import {
  YAxis,
  Tooltip,
  ResponsiveContainer,
  Area,
  AreaChart,
  XAxis,
} from "recharts";
import { useNavigate } from "react-router-dom";
import InfiniteScrollContent from "@/components/InfiniteScrollContentComponent/InfiniteScrollContentComponent";
import { getCurrencyPrice, getData, getSaleList } from "@/api/module/STC";

const HeaderComponent = () => {
  const { t } = useTranslation();

  return (
    <div className="text-center font-bold text-xl py-2">{t("SimuDou")}</div>
  );
};
const AssetsComponent = () => {
  const { t } = useTranslation();

  const [data, setData] = useState<Awaited<ReturnType<typeof getData>>["data"]>(
    {
      price: 0,
      balance: 0,
      min_amount: 0,
      max_amount: 0,
      amount_macthed: 0,
      amount_macthed_market: 0,
      amount_on_sale: 0,
    }
  );
  const reqData = async () => {
    const res = await getData();
    setData(res.data);
  };
  useEffect(() => {
    reqData();
  }, []);
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-3 px-5 bg-custom-gradient-1 rounded-xl relative -top-4">
        <div className="text-center font-semibold">{t("AIMatchingData")}</div>
        <div className="value flex justify-between mt-4">
          <div className="num">
            <div className="opacity-50 text-sm">{t("todayMatch")}</div>
            <div className="font-bold text-2xl">
              {data.amount_macthed_market}
            </div>
          </div>
          <div className="price">
            <div className="opacity-50 text-sm">{t("highestMatchPrice")}</div>
            <div className="font-bold text-2xl">{data.price}</div>
          </div>
        </div>
      </div>
    </div>
  );
};
const EchartComponent = () => {
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getCurrencyPrice>>["data"]["chart_data"]
  >([]);
  const reqCurrencyPrice = async () => {
    try {
      const res = await getCurrencyPrice({
        number: "7",
        currency: "GPB",
      });
      // res.data.chart_data = [
      //   {
      //     currency: 'GPB',
      //     price: 0.1,
      //     change_percent: '0%',
      //     create_time: 1735542794,
      //     gap: '2024-12-30',
      //   },
      //   {
      //     currency: 'GPB',
      //     price: 0.1,
      //     change_percent: '0%',
      //     create_time: 1735542794,
      //     gap: '2024-12-30',
      //   },
      //   {
      //     currency: 'GPB',
      //     price: 0.1,
      //     change_percent: '0%',
      //     create_time: 1735542794,
      //     gap: '2024-12-30',
      //   },
      //   {
      //     currency: 'GPB',
      //     price: 0.1,
      //     change_percent: '0%',
      //     create_time: 1735542794,
      //     gap: '2024-12-30',
      //   },
      // ];
      setData(
        res.data.chart_data.map((item) => {
          return {
            ...item,
            gap: item.gap.slice(-5),
          };
        })
      );
    } catch (error) {}
  };
  useEffect(() => {
    reqCurrencyPrice();
  }, []);
  return (
    <>
      {data.length > 0 ? (
        <div className="mt-4 text-sm w-full h-56 text-white-1">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart
              width={730}
              height={250}
              data={data}
              margin={{ top: 10, right: 10, left: -10, bottom: 0 }}
            >
              <defs>
                <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="30%" stopColor="#0889CD" stopOpacity={0.8} />
                  <stop offset="60%" stopColor="#02335E" stopOpacity={0.8} />
                  <stop offset="100%" stopColor="transparent" stopOpacity={0} />
                </linearGradient>
              </defs>
              <XAxis dataKey="gap" />
              <YAxis scale={"linear"} />
              {/* <CartesianGrid strokeDasharray="3 3" /> */}
              <Tooltip />
              <Area
                dot={{ stroke: "#D6FFFE", strokeWidth: 1 }}
                type="monotone"
                dataKey="price"
                stroke="#48BDF0"
                fillOpacity={1}
                fill="url(#colorUv)"
              />
            </AreaChart>
          </ResponsiveContainer>{" "}
        </div>
      ) : (
        ""
      )}
    </>
  );
};

const TransactionListComponent = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getSaleList>>["data"]["list_data"]
  >([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {
    const res = await getSaleList({
      type: "market",
      page: page + "",
    });
    console.log("交易清单");
    setHasMore(false);
    setPage((val) => val + 1);
    setData((val) => [...val, ...res.data.list_data]);
    setHasMore(+res.data.page_on < res.data.total_page);
  }
  return (
    <div className="mt-6">
      <div>{t("transactionList")}</div>
      <div className="tab text-center text-sm bg-bg-1 rounded-lg pb-3">
        <div className="tab-title">
          <div className="py-4 mt-2 flex items-center">
            <div className="w-1/2">{t("price")}</div>
            <div className="w-1/2">{t("num")}</div>
          </div>
        </div>
        <div className="tab-content text-white-1 max-h-80 overflow-y-scroll">
          {data.map((item, index) => (
            <div
              key={item.order_sn}
              className={`flex py-4 ${index % 2 == 1 ? "bg-bg-17" : "bg-black-1"}`}
            >
              <div className="w-1/2">{item.price}</div>
              <div className="w-1/2">{item.amount}</div>
            </div>
          ))}
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
            <InfiniteScrollContent hasMore={hasMore} />
          </InfiniteScroll>
        </div>
      </div>
      <div className="btn text-center">
        <div
          onClick={() => navigate("/digitalVoucherCenter")}
          className="bg-bg-16 py-3 rounded-md mt-4"
        >
          {t("sell")}
        </div>
      </div>
    </div>
  );
};

const LogsComponent = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [active, setActive] = useState(0);
  const tabList = ["myCurrentTransactionList"];
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getSaleList>>["data"]["list_data"]
  >([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {
    const res = await getSaleList({
      type: "market",
      page: page + "",
    });
    setPage((val) => val + 1);
    // const append2 = await Promise.resolve(append);
    setData((val) => [...val, ...res.data.list_data]);
    setHasMore(+res.data.page_on < res.data.total_page);
  }
  return (
    <div className="mt-4">
      <div className="flex justify-between items-center">
        <div className="tab flex">
          {tabList.map((item, index) => {
            return (
              <div
                key={item}
                className={`mr-4 ${active == index ? Styles["active"] : ""}`}
              >
                {t(item)}
              </div>
            );
          })}
        </div>

        <div>
          <Popover
            style={{
              // @ts-ignore
              "--background": "#000",
            }}
            content={
              <div className="text-white-1 px-4">
                <div
                  onClick={() => navigate("/STCRecord/buy")}
                  className="py-2 border-b"
                >
                  {t("STCBuyRecord")}
                </div>
                <div
                  onClick={() => navigate("/STCRecord/sell")}
                  className="py-2"
                >
                  {t("STCSellRecord")}
                </div>
              </div>
            }
            trigger="click"
            placement="bottom"
            defaultVisible={false}
          >
            <FileOutline color="#E99434" />
          </Popover>
        </div>
      </div>
      <div className="logs mt-6 text-sm">
        <div className="text-white-1 bg-bg-1 mb-4 rounded-lg p-4 ">
          {active == 0 ? (
            <div>
              <div className="logs-tab-title flex justify-between items-center ">
                <div className="w-2/5">{t("date")}</div>
                <div className="w-1/5">{t("type")}</div>
                <div className="w-1/5">{t("price")}</div>
                <div className="w-1/5">{t("amount")}</div>
              </div>
              <div className="logs-tab-content max-h-56 overflow-y-scroll">
                {data.map((item) => (
                  <div
                    key={item.order_id}
                    className="flex justify-between items-center py-2"
                  >
                    <div className="w-2/5">{item.create_time}</div>
                    <div className="w-1/5">
                      {item.currency === "GPB" ? "RWA" : item.currency}
                    </div>
                    <div className="w-1/5">{item.price}</div>
                    <div className="w-1/5">{item.amount}</div>
                  </div>
                ))}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                  <InfiniteScrollContent hasMore={hasMore} />
                </InfiniteScroll>
              </div>
            </div>
          ) : (
            <div className="text-center">
              <div className="logs-tab-title flex justify-between items-center ">
                <div className="w-1/2">{t("price")}</div>
                <div className="w-1/2">{t("num")}</div>
              </div>
              <div className="logs-tab-content max-h-56 overflow-y-scroll">
                {data.map((item) => (
                  <div
                    key={item.order_id}
                    className="flex justify-between items-center py-2"
                  >
                    <div className="w-1/2">{item.price}</div>
                    <div className="w-1/2">{item.amount}</div>
                  </div>
                ))}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                  <InfiniteScrollContent hasMore={hasMore} />
                </InfiniteScroll>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
export default function STC() {
  // i18n.changeLanguage('en');
  // const { t, i18n } = useTranslation();
  // const changeI18n = () => {
  //   i18n.changeLanguage(i18n.language == 'en' ? 'zh' : 'en');
  // };
  return (
    <div className="text-white-1 px-3 pb-28">
      <HeaderComponent />
      <AssetsComponent />
      <EchartComponent />
      <TransactionListComponent />
      <LogsComponent />
      {/* <span>{t('U2U')}</span>
      <button onClick={() => changeI18n()}>asd</button> */}
    </div>
  );
}
